import psycopg2
import psycopg2.extras
import sys
from shapely.geometry import box
from shapely.wkt import dumps, loads
import gdal
from gdalconst import *
import os
import constant

def re_griding(inputfile, ouputfile, resx=0.117292465957718, resy=-0.117292465957718):
	regrid_command = "gdalwarp -s_srs '+proj=longlat +datum=WGS84' -t_srs '+proj=longlat +datum=WGS84' -ot Int16 -wt Int16 -te 100.1 6.4 111.8 25.6 -tr {0} {1} -r cubic -overwrite {2} {3}".format(resx, resy, inputfile, ouputfile)
	os.system(regrid_command)
def mer_dem(inputfile, ouputfile, resx=0.117292465957718, resy=-0.117292465957718):
	con = None
	try:
		con = psycopg2.connect(host='192.168.3.4', database='fimo', user='rasdaman', password='rasdaman') 
		cur = con.cursor(cursor_factory=psycopg2.extras.DictCursor)
		cur.execute('SELECT filename, path, ST_AsText(corner) as corner FROM satorgdem limit 10')
		rows = cur.fetchall()
		
		merge_command = "python gdal_merge.py -o demorg.tif -ot Int16 -n 0 -a_nodata 0"
		for row in rows:
			filename = row["filename"].strip()
			filename=filename.replace(".tif","")
			
			path = row["path"].strip()
			path = os.path.join("/var/www/html/", path) #hardcode path to local folder path
			corner = loads(row["corner"])

			filepath = os.path.join(path, filename)
			merge_command += " " + filepath
		os.system(merge_command)

		#re_griding(inputfile, resx, resy, ouputfile)
		
	except psycopg2.DatabaseError, e:
		print 'Error %s' % e    
		sys.exit(1)
	finally:
		if con:
			con.close()	
if __name__ == '__main__':
	# main(sys.argv[1], sys.argv[2], sys.argv[3],  sys.argv[4])
	inputfile="/var/www/demorg.tif"
	outputfile="/var/www/dem.tif"
	resx=0.117292465957718
	resy=-0.117292465957718
	
	mer_dem(inputfile, outputfile, resx, resy)	
	
